package com.fsh.oss.util;

import com.fsh.oss.entity.FileInfo;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 作者：fsh
 * 日期：2023/10/26
 * <p>
 * 描述：minio工具类
 */
@Component
public class MinioUtil {
    /**
     * 注入 minio 的客户端
     */
    @Resource
    private MinioClient minioClient;

    /**
     * 创建bucket桶
     *
     * @param bucketName 存储桶名称
     */
    public void createBucket(String bucketName){
        //先判断是否存在这个桶
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if(!exists){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName)
                        .build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void createBucket2(String bucketName){
        //先判断是否存在这个桶
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if(!exists){
                PostPolicy policy=new PostPolicy(bucketName, ZonedDateTime.now().plusDays(7));
                policy.addStartsWithCondition("Content-Type","image/");
                policy.addContentLengthRangeCondition(64*1024,10*1024*1024);
                minioClient.getPresignedPostFormData(policy);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     */
    public void uploadFile(InputStream inputStream,String bucketName,String objectName){
        try{
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName).stream(inputStream,-1,5242889L)
                    .object(objectName).build());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 列出所有桶
     */
    public List<String> getAllBuckets(){
        try {
            List<Bucket> buckets = minioClient.listBuckets();
            return buckets.stream().map(Bucket::name).collect(Collectors.toList());
        }catch (Exception e){
            e.printStackTrace();
            return Collections.emptyList();
        }
    }


    /**
     * 列出当前桶的文件
     */
    public List<FileInfo> getAllFile(String bucketName){
        try{
            Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
            List<FileInfo> fileInfoList=new LinkedList<>();
            for (Result<Item> result : results) {
                FileInfo fileInfo=new FileInfo();
                Item item = result.get();
                //文件名
                fileInfo.setFileName(item.objectName());
                //是否 是目录
                fileInfo.setDirectoryFlag(item.isDir());
                fileInfo.setEtag(item.etag());
                fileInfoList.add(fileInfo);
            }
        return  fileInfoList;
        }catch (Exception e){
            e.printStackTrace();
            return Collections.emptyList();
        }
    }

    /**
     * 下载文件
     */
    public InputStream downLoad(String bucketName, String objectName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        return minioClient.getObject(
                GetObjectArgs.builder().bucket(bucketName).object(objectName).build()
        );
    }

    /**
     * 删除桶
     */
    public void deleteBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 删除文件
     */
    public void deleteObject(String bucket, String objectName) {
        try{
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucket).object(objectName).build());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * @param bucket     桶
     * @param objectName 对象名称
     *
     * 获取文件的  url
     */
    @SneakyThrows
    public String getPreviewFileUrl(String bucket, String objectName) {
        GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder().bucket(bucket).object(objectName).method(Method.GET).build();
        return minioClient.getPresignedObjectUrl(args);
    }
}
